#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 1005;

int n, m;
char g[N][N];
vector<pii> z;
pii boy, girl;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
bool check(int x, int y, int t) {
  if (x < 1 || x > n || y < 1 || y > m || g[x][y] == 'X') return false;
  for (pii p : z) {
    int dis = abs(x - p.first) + abs(y - p.second);
    if (dis <= t * 2) return false;
  }
  return true;
}
int vis[N][N];
int bfs() {
  memset(vis, 0, sizeof(vis));
  queue<pii> qb, qg;
  qb.push(boy), qg.push(girl);
  vis[boy.first][boy.second] = 1;
  vis[girl.first][girl.second] = 2;
  int t = 0;
  while (qb.size() || qg.size()) {
    t++;
    rep(_i, 0, 2) {
      queue<pii> tmp;
      while (qb.size()) {
        pii now = qb.front();
        qb.pop();
        int x = now.first, y = now.second;
        if (!check(x, y, t)) continue;
        rep(j, 0, 3) {
          int xx = x + dx[j], yy = y + dy[j];
          if (!check(xx, yy, t)) continue;
          if (vis[xx][yy] == 2) return t;
          if (!vis[xx][yy]) {
            vis[xx][yy] = 1;
            tmp.push(pii(xx, yy));
          }
        }
      }
      swap(qb, tmp);
    }
    rep(_i, 0, 0) {
      queue<pii> tmp;
      while (qg.size()) {
        pii now = qg.front();
        qg.pop();
        int x = now.first, y = now.second;
        if (!check(x, y, t)) continue;
        rep(j, 0, 3) {
          int xx = x + dx[j], yy = y + dy[j];
          if (!check(xx, yy, t)) continue;
          if (vis[xx][yy] == 1) return t;
          if (!vis[xx][yy]) {
            vis[xx][yy] = 2;
            tmp.push(pii(xx, yy));
          }
        }
      }
      swap(qg, tmp);
    }
  }
  return -1;
}
void solve() {
  cin >> n >> m;
  rep(i, 1, n) rep(j, 1, m) cin >> g[i][j];
  z.clear();
  rep(i, 1, n) rep(j, 1, m) {
    if (g[i][j] == 'M') boy = pii(i, j);
    if (g[i][j] == 'G') girl = pii(i, j);
    if (g[i][j] == 'Z') z.push_back(pii(i, j));
  }
  cout << bfs() << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}